/*
 * Copyright 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mediacloud.app.newsmodule.service.servicenotification;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import androidx.media.session.MediaButtonReceiver;

import android.support.v4.media.session.PlaybackStateCompat;
import android.util.Log;
import android.widget.RemoteViews;

import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.news.kt.TypeX;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.activity.AlbumAudioActivity;
import com.mediacloud.app.newsmodule.activity.AudioLiveDetailActivity;
import com.mediacloud.app.newsmodule.activity.AudioLiveDetailActivityHalf;
import com.mediacloud.app.newsmodule.activity.AudioVodDetailActivity;
import com.mediacloud.app.newsmodule.activity.ImageTextDetailActivity2;
import com.mediacloud.app.newsmodule.broadcast.AudioVodBroadcast;


/**
 * Keeps track of a notification and updates it automatically for a given MediaSession. This is
 * required so that the music service don't get killed during playback.
 */
public class MediaNotificationManager {
    public static final int TYPE_VOD = 0;
    public static final int TYPE_IMAGE_TEXT=1;
    public static final int TYPE_ALBUM = 2;
    public static final int TYPE_LIVE=3;
    public static final int TYPE_VIDEO = 4;

    public static final int NOTIFICATION_ID = 499;

    private static final String TAG = MediaNotificationManager.class.getSimpleName();
    private static final int REQUEST_CODE = 521;

    private final Service mService;
    private int mType;

    //    private final NotificationCompat.Action mPlayAction;
//    private final NotificationCompat.Action mPauseAction;
//    private final NotificationCompat.Action mNextAction;
//    private final NotificationCompat.Action mPrevAction;
    private final NotificationManager mNotificationManager;
    private final String CHANNEL_ID;
    private ArticleItem currentArticleItem;
    private CatalogItem catalogItem;
    private CatalogItem navigate;
    private boolean isPlaying;

    public void setmType(int mType) {
        this.mType = mType;
    }

    public MediaNotificationManager(Service service, int type) {
        mService = service;
        mType = type;
        CHANNEL_ID = service.getPackageName();
        mNotificationManager =
                (NotificationManager) mService.getSystemService(Context.NOTIFICATION_SERVICE);


        // Cancel all notifications to handle the case where the Service was killed and
        // restarted by the system.
        mNotificationManager.cancelAll();
    }

    public void onDestroy() {
        Log.w(TAG, "onDestroy: ");
    }

    public NotificationManager getNotificationManager() {
        return mNotificationManager;
    }

    public Notification getNotification(ArticleItem articleItem, boolean isPlaying) {
        if (articleItem == null) {
            Log.e(TAG, "articleItem is null");
        }
        currentArticleItem = articleItem;
        this.isPlaying = isPlaying;
        NotificationCompat.Builder builder =
                buildNotification(isPlaying, articleItem, null);
        return builder.build();
    }

    public Notification getNotification(ArticleItem articleItem, boolean isPlaying, Bitmap logoBitmap) {
        if (articleItem == null) {
            Log.e(TAG, "articleItem is null");
        }
        currentArticleItem = articleItem;
        this.isPlaying = isPlaying;
        NotificationCompat.Builder builder =
                buildNotification(isPlaying, articleItem, logoBitmap);
        return builder.build();
    }

    public void setCatalogItem(CatalogItem catalogItem) {
        this.catalogItem = catalogItem;
    }

    private NotificationCompat.Builder buildNotification(boolean isPlaying, ArticleItem description, Bitmap logoBitmap) {

        // Create the (mandatory) notification channel when running on Android Oreo.
        if (isAndroidOOrHigher()) {
            createChannel();
        }
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(mService, CHANNEL_ID);
        final RemoteViews normalRemoteViews = new RemoteViews(mService.getPackageName(), R.layout.normal_notification);
        normalRemoteViews.setImageViewResource(R.id.ib_toggle, isPlaying ? R.drawable.audio_play_pause_btn : R.drawable.audio_play_btn);
        normalRemoteViews.setOnClickPendingIntent(R.id.ib_toggle, createStopIntent());
        if (description != null) {
            normalRemoteViews.setTextViewText(R.id.tv_audio_title, description.getTitle());
        }
        if (logoBitmap != null) {
            normalRemoteViews.setImageViewBitmap(R.id.image_icon, logoBitmap);
        }
        builder
                .setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE)
                .setVibrate(new long[]{0})
                .setSound(null) //置空缺陷不处理
                .setCustomContentView(normalRemoteViews)
                .setSmallIcon(R.drawable.ic_launcher)
                .setShowWhen(false)
                .setColor(ContextCompat.getColor(mService, R.color.notification_bg))
                .setContentIntent(createContentIntent())
                .setDeleteIntent(MediaButtonReceiver.buildMediaButtonPendingIntent(
                        mService, PlaybackStateCompat.ACTION_STOP))
                // Show controls on lock screen even when user hides sensitive content.
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC);

        return builder;
    }

    // Does nothing on versions of Android earlier than O.
    @RequiresApi(Build.VERSION_CODES.O)
    private void createChannel() {
        if (mNotificationManager.getNotificationChannel(CHANNEL_ID) == null) {
            // The user-visible name of the channel.
            CharSequence name = "MediaSession";
            // The user-visible description of the channel.
            String description = "MediaSession and MediaPlayer";
            int importance = NotificationManager.IMPORTANCE_LOW;
            NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
            // Configure the notification channel.
            mChannel.setDescription(description);
            mChannel.enableLights(false);
            // Sets the notification light color for notifications posted to this
            // channel, if the device supports this feature.
            mChannel.setLightColor(Color.RED);
            mChannel.enableVibration(false);
            mChannel.setVibrationPattern(new long[]{0});
            mChannel.setSound(null, null);
            mNotificationManager.createNotificationChannel(mChannel);
            Log.w(TAG, "createChannel: New channel created");
        } else {
            Log.w(TAG, "createChannel: Existing channel reused");
        }
    }

    private boolean isAndroidOOrHigher() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O;
    }

    private PendingIntent createContentIntent() {
        Intent openUI;
        if (mType == TYPE_VOD) {//音频点播
            openUI = new Intent(mService, AudioLiveDetailActivityHalf.class);
            openUI.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            openUI.putExtra("fromAudioWinUtils", true);
            openUI.putExtra("data", currentArticleItem);
            openUI.putExtra("isPlaying", isPlaying);
            if (catalogItem != null) {
                openUI.putExtra("catalog", catalogItem);
            }
        } else if (mType == TYPE_IMAGE_TEXT) {//图文
            openUI = new Intent(mService, ImageTextDetailActivity2.class);
            openUI.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            openUI.putExtra("data", currentArticleItem);
            if (catalogItem != null) {
                openUI.putExtra("catalog", catalogItem);
            }
        } else if (mType == TYPE_ALBUM) {//专题
            openUI = new Intent(mService, AlbumAudioActivity.class);
            openUI.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            if (catalogItem != null) {
                openUI.putExtra("data", catalogItem);
            }
            if (navigate != null) {
                openUI.putExtra("data", navigate);
            }
        } else {//直播
            openUI = new Intent(mService, AudioLiveDetailActivityHalf.class);
            currentArticleItem.setType(TypeX.NEWS.LIVE_AUDIO);
            openUI.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            openUI.putExtra("fromAudioWinUtils", true);
            openUI.putExtra("data", currentArticleItem);
            if (currentArticleItem != null)
                openUI.putExtra("ChatRoomOpen", currentArticleItem.chatRoomOpen > 0 ? true : false);
            openUI.putExtra("isPlaying", isPlaying);
            if (catalogItem != null) {
                openUI.putExtra("catalog", catalogItem);
            }
        }
        return PendingIntent.getActivity(
                mService, REQUEST_CODE, openUI, PendingIntent.FLAG_UPDATE_CURRENT);
    }

    private PendingIntent createStopIntent() {
        Intent stopAudio = new Intent();
        stopAudio.setAction(AudioVodBroadcast.TOGGLE_AUDIO);
        return PendingIntent.getBroadcast(mService, REQUEST_CODE, stopAudio, PendingIntent.FLAG_UPDATE_CURRENT);
    }

    public void setAlbumNavigate(CatalogItem navigate) {
        this.navigate = navigate;
    }

}